if(window.jQuery && window.jQuery.PPF && !window.jQuery.PPF.kaoshi) {
	(function($){
		$PPF.extend({
			kaoshi : {
				data: []
				,nododata: []
				,donedata: []
				,dotype: 0	//0 all 1 done 2 nodo
				,page: 1
				,pagesize: 20
				,totalpage: 0
				,kjdata: null
				,sjdata: null
				,daan: null
				,shitis: null
				,stypes: null
				,lastsave: 0
				,savespace: 300
				,saving: false
				,nobeat: false
				,config: function( param ){
					this.stypes = typeof param.stypes == "object" ? param.stypes : null;
					this.sjdata = typeof param.sjdata == "object" ? param.sjdata : null;
					this.kjdata = typeof param.kjdata == "object" ? param.kjdata : null;
					if(typeof this.sjdata.pagesize == "number") this.pagesize = this.sjdata.pagesize;
					this.lastsave = this.savespace - (__System.time - this.lastsave) < 1 ? __System.time : this.kjdata.lastupdate;
					if( 0 == this.pagesize ) {this.pagesize = Number.MAX_VALUE}
					else this.pagesize = Math.max(1,this.pagesize);
					for(var e in this.kjdata.stdata) {
						this.data[this.data.length] = $.extend( true,{ xtid: e },this.kjdata.stdata[e] );
					}
					this.initThao();
					this.daan = $.extend( true,{},this.kjdata.daandata );
					this.initDoneData();
					this.totalpage = Math.ceil( this.data.length / this.pagesize);
					PPF.kaoshi.heartBeat();
				}
				,setDotype: function(t){	//设置已答、未答、全部
					if(t === this.dotype) return;
					if(t == 1 || t == 2) this.dotype = t;
					else this.dotype=0;
					this.recordDaan();
					this.initPage();
					var guid;
					switch(this.dotype){
						case 1:
							guid = '<a href="javascript:;" onclick="PPF.kaoshi.setDotype(0)" class="phover">全部</a><span class="pcur">已答</span><a href="javascript:;"  class="phover" onclick="PPF.kaoshi.setDotype(2)">未答</a>';
							break;
						case 2:
							guid = '<a href="javascript:;" onclick="PPF.kaoshi.setDotype(0)"  class="phover">全部</a><a href="javascript:;" onclick="PPF.kaoshi.setDotype(1)"  class="phover">已答</a><span class="pcur">未答</span>';
							break;
						default:
							guid = '<span class="pcur">全部</span><a href="javascript:;" onclick="PPF.kaoshi.setDotype(1)"  class="phover">已答</a><a href="javascript:;" onclick="PPF.kaoshi.setDotype(2)" class="phover">未答</a>';
							break;
					}
					this.init(1);
					$("#kaoshiPageLink div.dotype").empty().append(guid);
				}
				,initDoneData: function(){
					this.donedata = [];
					this.nododata = [];
					for(var i=0;i<this.data.length;i++){	//just 引用
						if( this.daan[ this.data[i].xtid ] )
							this.donedata[this.donedata.length] = this.data[i];
						else 
							this.nododata[this.nododata.length] = this.data[i];
					}
				}
				,initPage: function(){
					this.page = 1;
					var data;
					switch(this.dotype){
						case 1:
							data = this.donedata;break;
						case 2:
							data = this.nododata;break;
						default:
							data = this.data;break;
					}
					this.totalpage = Math.ceil( data.length / this.pagesize);
				}
				,initThao: function(){	//初始化题号
					var th = 1;
					for(var id in this.sjdata.d_dlmix){
						for(var i=0;i<this.data.length;i++){
							if(this.data[i].did == id) {	//todo 考虑组合题
								this.data[i].thao = th++;
							}
						}
					}
				}
				,init: function(p){
					p = typeof p == "number" ? p : 1;
					p = Math.max(1,Math.min(this.totalpage,p));
					var st=this.pagesize * (p -1);
					this.truncateContainer();
					var data;
					switch(this.dotype){
						case 1:
							data = this.donedata;break;
						case 2:
							data = this.nododata;break;
						default:
							data = this.data;break;
					}
					var end = Math.min(st + this.pagesize - 1,data.length-1);
					if(end >= st){
						for(var i=st;i<=end;i++){
							this.appendShiti( data[i] );
						}
						$("#kaoshiEtemList input[type='radio']").radiotg();
					}else{
						this.noShiti();
					}
					this.page = p;
					this.initPageLink();
				}
				,noShiti: function(){
					var str;
					switch(this.dotype){
						case 1:
							str = "所有题目都还没有作答！";break;
						case 2:
							str = "所有题目都答完了！";break;
						default:
							str = "一定是出错了，一个题目都没有！";break;
					}
					$("#kaoshiEtemList").append('<div class="noshiti">' + str + '</div>');
				}
				,sinit: function(p){	//save & init
					this.recordDaan();
					this.initPage();
					this.init(p);
				}
				,getStType: function(t){
					try{ return this.stypes[t].tixing; }catch(e){ return 'danxuan'; }
				}
				,getDuanData: function(id){
					var d = this.sjdata.d_dlmix;
					if(typeof d[id] == "object"){
						var dd = d[id];
						dd.id = id;
						return dd;
					}
					return null;
				}
				,appendShiti: function( data ){
					var c=$("#_duanContainer_"+data.did);
					if(c.size() < 1) {
						var d = this.getDuanData(data.did);
						$("#kaoshiEtemList").append($("#kaoshiduan_tpl").content({
							id: d.id
							,title: d.t
							,d: d.d
						}));
						c=$("#_duanContainer_"+data.did);
					}
					$(".shitiContain",c).append( this.createShitiEtem(data) );
				}
				,initPageLink: function(){
					if(this.totalpage < 2) {$(".pages").empty();return;};
					var n = 2;
					var s = '';
					$(".pages").empty();
					if(this.pagesize == 1){
						if(this.page > 1 ) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit('+(this.page-1)+')">上一题</a>';
						else s += '<a href="javascript:;" class="hidden">上一题</a>';
						if(this.page < this.totalpage) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit('+(this.page+1)+')">下一题</a>';
					}else {
						if(this.page > 1 ) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit('+(this.page-1)+')">上一页</a>';
						else s += '<a href="javascript:;" class="hidden">上一页</a>';
						if(this.page > n+1) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit(1)">1</a>';
						if(this.page - 2 > n) s+= '<span class="more"> ... </span>';
						for(var i=1;i<=this.totalpage;i++){
							if(this.page == i) s += '<span class="current">' + i + '</span>';
							else if( Math.abs(this.page-i) <= n ) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit(' + i + ')">' + i + '</a>';
						}
						if(this.totalpage - this.page - 1 > n) s += '<span class="more"> ... </span>';
						if(this.page < this.totalpage -n) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit(' + this.totalpage + ')">' + this.totalpage + '</a>';
						if(this.page < this.totalpage) s += '<a href="javascript:;" onclick="PPF.kaoshi.sinit('+(this.page+1)+')">下一页</a>';
					}
					$(".pages").append(s);
				}
				,recordDaan: function(){
					var _t = this;
					$("li[id^='_shitiItem_']").each(function(){
						var id = $(this).attr('id').substr('_shitiItem_'.length);
						var data = _t.kjdata.stdata[id];
						switch(_t.getStType(data.type)){
							case 'danxuan':
								var st = $("input[name='st_"+id+"']:checked",this);
								if(st.size() > 0) _t.daan[id] = st.val();
								else delete _t.daan[id];
								break;
							case 'duoxuan':
								var st = $("input[name='st_"+id+"']:checked",this);
								if(st.size() > 0) {
									_t.daan[id] = {};
									st.each(function(){
										_t.daan[id][$(this).val()] = $(this).val();
									});
								}
								else delete _t.daan[id];
								break;
							case 'xinli':
								var st = $("input[name='st_"+id+"']:checked",this);
								if(st.size() > 0) _t.daan[id] = st.val();
								else delete _t.daan[id];
								break;
							case 'jianda':
								var d = $("textarea[name='st_"+id+"']",this).val();
								if(d) _t.daan[id] = d;else delete _t.daan[id];
								break;
						}
					});
					this.initDoneData();
				}
				,createShitiEtem: function(data){
					var content = 'loading...';
					var title = data.title;
					var id = data.xtid;
					var _t = this;
					switch( this.getStType(data.type) ){
						case 'danxuan':
							content = PPF.html.radios({
								options: data.xx,
								checked: _t.daan[data.xtid],
								name:'st_'+id,
								_key: "k",
								_val: "xx",
								abc: true,
								label_ids: true
							});// + '<div>&nbsp;</div>';
							var ext = "分值："+ PPF.formatFen(data.fen);
							//if(data.kf>0) 
							ext += " 答错扣" + PPF.formatFen(data.kf) + "分 ";
							title = title + "（" + ext + "）";
							break;
						case 'duoxuan':
							content = PPF.html.checkboxes({
								options: data.xx,
								checked: _t.daan[data.xtid],
								name:'st_'+id,
								noadd:true,
								_key: "k",
								_val: "xx",
								abc: true,
								label_ids: true
							});// + '<div>&nbsp;</div>';
							var ext = "分值："+ PPF.formatFen(data.fen);
							//if(data.kf>0) 
							ext += " 答错扣" + PPF.formatFen(data.kf) + "分 ";
							//if(data.hfen>0) 
							ext += " 少选得" + PPF.formatFen(data.hfen) + "分 ";
							title = title + "（" + ext + "）";
							break;
						case 'xinli':
							var xx = {};
							for(var e in data.xx){
								var tmp = {k:data.xx[e].k,xx:data.xx[e].xx };
								xx[e] = tmp;
							}
							content = PPF.html.radios({
								options: xx,
								checked: _t.daan[data.xtid],
								name:'st_'+id,
								_key: "k",
								_val: "xx",
								abc: true,
								label_ids: true
							});// + '<div>&nbsp;</div>';
							break;
						case 'jianda':
							content = '<textarea name="st_' + id + '" rows="5" cols="60" class="jiandaInput" style="width:90%;">' + (_t.daan[data.xtid] ? _t.daan[data.xtid] : '') + '</textarea>';
							var ext = "分值："+ PPF.formatFen(data.fen);
							title = title + "（" + ext + "）";
							break;
					}
					return $("#shiti_tpl").content({
						title:title,
						content: content,
						thao: data.thao,
						//jieda: data.jieda,
						id: id
					});
				}
				,truncateContainer: function(){
					$("#kaoshiEtemList").empty();
				}
				,heartBeat: function(){
					if(this.nobeat) return;
					this.changeTime();
					this.guidPosition();
					this.autoSaveUpdate();
					if(this.kjdata.kaoshiend - __System.time < 1.5){
						this.submit(true);
						return;
					}
					setTimeout( function(){PPF.kaoshi.heartBeat()} , 499 );
				}
				,changeTime: function(){
					$("#kaoshiGuid span[key='dotime']").html( PPF.timeFormate(this.sjdata.dotime) );
					$("#kaoshiGuid span[key='leavetime']").html(PPF.timeFormate( this.kjdata.kaoshiend - __System.time ));
				}
				,guidPosition: function(){
					$("#kaoshiGuid").css({top:($(window).height()*2)/7 + $(window).scrollTop(),left:20,display:"block"});
				}
				,autoSaveUpdate: function(){
					if(this.lastsave > 0){
						var s = this.savespace - (__System.time - this.lastsave);
						$("#kaoshiGuid span[key='lastsave']").html(new Date( this.lastsave * 1000 ).toPPFstring('hh:ii:ss'));
						$("#kaoshiGuid span[key='autosave']").html(PPF.timeFormate(s));
					}else{
						var s = this.savespace - (__System.time - __System.__Loadtime);
						$("#kaoshiGuid span[key='lastsave']").html("无");
						$("#kaoshiGuid span[key='autosave']").html(PPF.timeFormate(s));
					}
					if(s>0 && s < 1){
						this.save();
					}
				}
				,save: function(){
					if(this.saving) return;
					this.recordDaan();
					var _t = this;
					var param = this.execModifyed();
					if(param){
						this.saving = true;
						var p = PPF.param( {d:param} );
						p.kjid = this.kjdata.id;
						$.post(__System.roots.exam + 'kaoshi/do' , p , function(data){
							if(data._code == 0){
								PPF.tips( {msg:"保存成功" , timeout: 2000} );
								_t.kjdata.daandata = $.extend( true , {} , _t.daan );
								_t.lastsave = __System.time;
								_t.saving = false;
							}else{
								//error!
								_t.saving = false;
								PPF.tips( {msg: PPF.jsonmsg(data,"系统繁忙") , timeout:3000 , type:1});
							}
						},'json');
					}else{
						_t.lastsave = __System.time;
						PPF.tips( { msg: "没有需要保存的答案", timeout: 3000, type: 1} );
					}
				}
				,submit: function(t){
					this.recordDaan();
					if(this.nododata.length > 0 && !t){
						PPF.dialog({msg:"您还有没有做完的题目，确认要交卷吗？",title:"确认交卷",type:2,focus:1,button:"确认交卷",cancel:"返回继续答题" , callback: function(){PPF.kaoshi.submit(1);} } );
					}else{
						var param = this.execModifyed();
						var p = PPF.param( {d:param} );
						p.kjid = this.kjdata.id;
						$.post(__System.roots.exam + 'kaoshi/submit' , p , function(data){
							if(data._code == 0){
								PPF.tips( {msg: PPF.jsonmsg(data,"交卷成功") , timeout: 2000} );
								setTimeout(function(){ location.href=__System.roots.exam + 'my/kaojuan' },1000);
							}else{
								//error
								PPF.tips( {msg: PPF.jsonmsg(data,"系统繁忙") , timeout:3000 , type:1});
							}
						},'json');
					}
				}
				,execModifyed: function(){
					var md = null;
					var d = this.kjdata.daandata;
					var da = this.daan;
					if(typeof d == "object" && d ){
						for(var e in d){
							if(typeof da[e] == "undefined") {		//查找清除掉的答案
								if(null === md) md = {};
								md[e] = '';
							}
						}
					}
					if(typeof da == "object" && da) {
						for(var e in da){
							if( !d || typeof d[e] == "undefined" || !PPF.compObject(da[e],d[e]) ){
								if(null === md) md = {};
								md[e] = da[e];
							}
						}
					}
					return md;
				}
			}
		});
	})(jQuery);
}